<!DOCTYPE html>
<html>
<head>
    <title>Pixel Art Board</title>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Roboto', sans-serif;
            display: flex;
            height: 100vh;
            background: #f0f2f5;
            overflow: hidden;
        }

        .board-container {
            flex: 1;
            position: relative;
            overflow: hidden;
        }

        .board {
            position: absolute;
            background-image: 
                linear-gradient(rgba(0, 0, 0, 0.1) 1px, transparent 1px),
                linear-gradient(90deg, rgba(0, 0, 0, 0.1) 1px, transparent 1px);
            background-size: {{ pixel_size }}px {{ pixel_size }}px;
            transform-origin: 0 0;
            transition: transform 0.2s ease-out;
            cursor: grab;
        }

        .board:active {
            cursor: grabbing;
        }

        .pixel {
            width: {{ pixel_size }}px;
            height: {{ pixel_size }}px;
            position: absolute;
            transition: background-color 0.3s ease, transform 0.1s ease;
            cursor: pointer;
        }

        .pixel:hover {
            transform: scale(1.1);
            z-index: 1;
        }

        .sidebar {
            width: 300px;
            background: white;
            padding: 2rem;
            box-shadow: -2px 0 10px rgba(0, 0, 0, 0.1);
            z-index: 2;
        }

        .color-picker {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 1rem;
            margin-top: 2rem;
        }

        .color-option {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            cursor: pointer;
            transition: transform 0.2s ease;
            border: 3px solid transparent;
            box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
        }

        .color-option:hover {
            transform: scale(1.1);
        }

        .color-option.selected {
            border-color: #333;
        }

        .timer {
            position: fixed;
            bottom: 2rem;
            right: 2rem;
            background: white;
            padding: 1rem 2rem;
            border-radius: 50px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            font-size: 1.2rem;
            color: #666;
        }

        /* 添加自定义颜色样式 */
       .custom-color {
            margin-top: 2rem;
            padding-top: 2rem;
            border-top: 1px solid #eee;
        }

        input[type="color"] {
            height: 40px;
            border: 2px solid #ddd;
            border-radius: 8px;
            cursor: pointer;
        }

        input[type="text"] {
            border: 2px solid #ddd;
            border-radius: 8px;
            font-family: monospace;
        }
    </style>
</head>
<body>
    <div class="board-container">
        <div class="board" id="board"></div>
    </div>
    <div class="sidebar">
        <h1>Pixel Art Board</h1>
        
        <!-- 预设颜色 -->
        <div class="color-picker" id="colorPicker"></div>
        
        <!-- 自定义颜色 -->
        <div class="custom-color">
            <input type="color" id="customColorInput" 
                   style="width: 100%; margin-top: 1rem">
            <input type="text" id="colorTextInput" 
                   placeholder="#FFFFFF" 
                   style="width: 100%; margin-top: 0.5rem; padding: 0.5rem">
        </div>
    </div>
    <div class="timer" id="timer">Ready to draw!</div>

    <script>
        const colors = [
            '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4',
            '#FFEEAD', '#FF9999', '#77DD77', '#AEC6CF'
        ];
        
        let selectedColor = colors[0];
        let cooldown = false;
        let offsetX = 0;
        let offsetY = 0;
        let scale = 1;
        let isDragging = false;
        let startX, startY;
        let customColors = [];

        function initBoard() {
            const board = document.getElementById('board');
            const boardSize = {{ board_size }};
            const pixelSize = {{ pixel_size }};

            // 设置画板基础尺寸
            board.style.width = `${boardSize * pixelSize}px`;
            board.style.height = `${boardSize * pixelSize}px`;

            // 创建像素
            for(let y = 0; y < boardSize; y++) {
                for(let x = 0; x < boardSize; x++) {
                    const pixel = document.createElement('div');
                    pixel.className = 'pixel';
                    pixel.style.left = `${x * pixelSize}px`;
                    pixel.style.top = `${y * pixelSize}px`;
                    pixel.dataset.x = x;
                    pixel.dataset.y = y;
                    
                    pixel.addEventListener('click', handlePixelClick);
                    board.appendChild(pixel);
                }
            }

            // 初始化颜色选择器
            initColorPicker();
        }

        function initCanvasControl() {
            const board = document.getElementById('board');
            
            // 鼠标事件处理
            board.addEventListener('mousedown', (e) => {
                isDragging = true;
                startX = e.clientX - offsetX;
                startY = e.clientY - offsetY;
                board.style.cursor = 'grabbing';
            });

            document.addEventListener('mousemove', (e) => {
                if (!isDragging) return;
                offsetX = e.clientX - startX;
                offsetY = e.clientY - startY;
                updateBoardTransform();
            });

            document.addEventListener('mouseup', () => {
                isDragging = false;
                board.style.cursor = 'grab';
            });

            // 缩放处理
            board.addEventListener('wheel', (e) => {
                e.preventDefault();
                const rect = board.getBoundingClientRect();
                const mouseX = e.clientX - rect.left;
                const mouseY = e.clientY - rect.top;
                
                const delta = e.deltaY > 0 ? 0.9 : 1.1;
                const newScale = Math.min(Math.max(0.5, scale * delta), 3);
                
                // 计算缩放中心偏移
                offsetX = mouseX - (mouseX - offsetX) * (newScale / scale);
                offsetY = mouseY - (mouseY - offsetY) * (newScale / scale);
                scale = newScale;
                
                updateBoardTransform();
            });
        }

        function updateBoardTransform() {
            const board = document.getElementById('board');
            board.style.transform = `translate(${offsetX}px, ${offsetY}px) scale(${scale})`;
        }

        async function handlePixelClick(e) {
            if(cooldown) return;
            
            const board = document.getElementById('board');
            const container = document.querySelector('.board-container');
            
            // 获取精确的坐标参考系
            const containerRect = container.getBoundingClientRect();
            const boardRect = board.getBoundingClientRect();
            
            // 计算缩放后的实际像素尺寸
            const scaledPixelSize = {{ pixel_size }} * scale;
            
            // 计算相对于画布容器的坐标
            const mouseX = e.clientX - containerRect.left;
            const mouseY = e.clientY - containerRect.top;
            
            // 转换为画布本地坐标（考虑平移和缩放）
            const localX = (mouseX - offsetX) / scale;
            const localY = (mouseY - offsetY) / scale;
            
            // 计算实际像素坐标
            const x = Math.floor(localX / {{ pixel_size }});
            const y = Math.floor(localY / {{ pixel_size }});
            
            // 边界检查
            if(x < 0 || x >= {{ board_size }} || y < 0 || y >= {{ board_size }}) {
                console.warn('Out of bounds:', x, y);
                return;
            }

            try {
                const response = await fetch('/update_pixel', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({x, y, color: selectedColor})
                });

                const data = await response.json();
                if(response.status === 429) {
                    showCooldown(data.remaining);
                    return;
                }

                if(response.ok) {
                    updatePixelDisplay(x, y, selectedColor);
                    startCooldown();
                }
            } catch(err) {
                console.error('Error:', err);
            }
        }

        function updatePixelDisplay(x, y, color) {
            const pixels = document.querySelectorAll('.pixel');
            const index = y * {{ board_size }} + x;
            if(pixels[index]) {
                pixels[index].style.backgroundColor = color;
            }
        }

        function startCooldown() {
            cooldown = true;
            let seconds = 15;
            const timer = document.getElementById('timer');
            
            const interval = setInterval(() => {
                timer.textContent = `Next pixel in ${seconds}s`;
                seconds--;
                
                if(seconds < 0) {
                    clearInterval(interval);
                    timer.textContent = "Ready to draw!";
                    cooldown = false;
                }
            }, 1000);
        }

        async function loadPixels() {
            const response = await fetch('/get_pixels');
            const pixels = await response.json();
            
            Object.entries(pixels).forEach(([key, color]) => {
                const [x, y] = key.split('-');
                const pixel = document.querySelector(`[data-x="${x}"][data-y="${y}"]`);
                if(pixel) pixel.style.backgroundColor = color;
            });
        }

        // 初始化颜色选择器
        function initColorPicker() {
            const colorPicker = document.getElementById('colorPicker');
            colors.forEach(color => {
                const colorOption = document.createElement('div');
                colorOption.className = 'color-option';
                colorOption.style.backgroundColor = color;
                colorOption.addEventListener('click', () => {
                    document.querySelectorAll('.color-option').forEach(opt => 
                        opt.classList.remove('selected'));
                    colorOption.classList.add('selected');
                    selectedColor = color;
                });
                colorPicker.appendChild(colorOption);
            });
            colorPicker.firstChild.classList.add('selected');

            // 自定义颜色处理
            const colorInput = document.getElementById('customColorInput');
            const textInput = document.getElementById('colorTextInput');
            
            colorInput.addEventListener('input', (e) => {
                selectedColor = e.target.value.toUpperCase();
                textInput.value = selectedColor;
                updateSelectedStyle(selectedColor);
            });
            
            textInput.addEventListener('change', (e) => {
                const color = validateColor(e.target.value);
                if(color) {
                    selectedColor = color;
                    colorInput.value = color;
                    updateSelectedStyle(color);
                }
            });
        }

        function validateColor(value) {
            const colorRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
            return colorRegex.test(value) ? value.toUpperCase() : null;
        }

        function updateSelectedStyle(color) {
            document.querySelectorAll('.color-option').forEach(opt => {
                opt.classList.remove('selected');
                if(opt.style.backgroundColor === color) {
                    opt.classList.add('selected');
                }
            });
        }

        // 初始化
        initBoard();
        initCanvasControl();
        loadPixels();
        initColorPicker();
    </script>
</body>
</html>